package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LevelListDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.SeekBar;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.jaygoo.widget.OnRangeChangedListener;
import com.jaygoo.widget.RangeSeekBar;
import com.otaliastudios.cameraview.BitmapCallback;
import com.otaliastudios.cameraview.CameraException;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Audio;
import com.otaliastudios.cameraview.controls.Facing;
import com.otaliastudios.cameraview.controls.Flash;
import com.otaliastudios.cameraview.controls.Mode;
import com.otaliastudios.cameraview.size.SizeSelector;
import com.otaliastudios.cameraview.size.SizeSelectors;
import com.stark.camera.kit.databinding.ActivityCkCameraBinding;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.utils.MediaLoadManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityCameraBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.DensityUtil;
import stark.common.basic.utils.FastClickUtil;
import stark.common.basic.utils.ProgressConvertUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class CameraActivity extends BaseAc<ActivityCameraBinding> {

    private CameraOptions mCameraOptions;
    private List<Flash> mFlashList;
    private String imgPath;



    @Override
    protected int onCreate() {
        return R.layout.activity_camera;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent5(this, mDataBinding.event1Container);
        mDataBinding.ivCameraBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivCameraFlash.setOnClickListener(this);
        mDataBinding.ivSelPic.setOnClickListener(this);
        mDataBinding.ivCameraStart.setOnClickListener(this);
        mDataBinding.ivCameraReversal.setOnClickListener(this);
        //亮度调节
        float maxProgress = mDataBinding.rsbBrightness.getMaxProgress();
        float minProgress = mDataBinding.rsbBrightness.getMinProgress();
        mDataBinding.rsbBrightness.setProgress((maxProgress - minProgress) / 2);
        mDataBinding.rsbBrightness.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                if (isFromUser && mCameraOptions != null) {
                    float exposureMinValue = mCameraOptions.getExposureCorrectionMinValue();
                    float exposureMaxValue = mCameraOptions.getExposureCorrectionMaxValue();
                    float value = ProgressConvertUtil.progress2value((int) leftValue, exposureMinValue, exposureMaxValue,
                            (int) view.getMaxProgress());
                    mDataBinding.cameraView.setExposureCorrection(value);
                }
            }

            @Override
            public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {
            }

            @Override
            public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {
            }
        });
    }

    @Override
    protected void onClickCallback(View v) {
        if (FastClickUtil.isFastClick()) return;
        switch (v.getId()){
            case R.id.ivCameraStart:
                if (mDataBinding.cameraView.isTakingPicture()) return;
                mDataBinding.cameraView.takePictureSnapshot();
                break;
            case R.id.ivCameraFlash:
                clickFlash();
                break;
            case R.id.ivSelPic:
                SelPicActivity.isMore=false;
                startActivity(SelPicActivity.class);
                break;
            case R.id.ivCameraReversal:
                reversalLens();
                break;
        }
    }

    @Override
    protected void initData() {
        getPermission();
        //获取图片
        getData();
    }

    private void getPermission() {
        StkPermissionHelper.permission(Manifest.permission.CAMERA).reqPermissionDesc(getString(R.string.get_camera_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                //初始化相机
                initCameraView();
            }

            @Override
            public void onDenied(boolean needGoSettings) {
                ToastUtils.showShort(R.string.no_permission);
            }
        }).request();
    }

    //初始化相机
    private void initCameraView() {
        mDataBinding.cameraView.setMode(Mode.PICTURE);
        mDataBinding.cameraView.setLifecycleOwner(this);
        mDataBinding.cameraView.setAudio(Audio.OFF);
        int width = DensityUtil.getWith(mContext);
        int height = DensityUtil.getHeight(mContext);
        SizeSelector maxAreaSelector = SizeSelectors.maxArea(width * height);
        SizeSelector equalWidthSelector = SizeSelectors.withFilter(size -> size.getWidth() == width);
        mDataBinding.cameraView.setPictureSize(SizeSelectors.and(maxAreaSelector, equalWidthSelector));
        mDataBinding.cameraView.addCameraListener(new CameraListener() {
            @Override
            public void onCameraOpened(@NonNull CameraOptions options) {
                updateOnCameraOpened(options);
            }

            @Override
            public void onCameraClosed() {
                mCameraOptions = null;
            }

            @Override
            public void onCameraError(@NonNull CameraException exception) {
                mCameraOptions = null;
            }

            @Override
            public void onPictureTaken(@NonNull PictureResult result) {
                //获取图片 去到预览界面
                int picWidth = result.getSize().getWidth();
                int picHeight = result.getSize().getHeight();
                int screenWidth = DensityUtil.getWith(mContext);
                int screenHeight = DensityUtil.getHeight(mContext);
                if (picWidth * picHeight > screenWidth * screenHeight) {
                    picWidth = screenWidth;
                    picHeight = screenHeight;
                }
                result.toBitmap(picWidth, picHeight, new BitmapCallback() {
                    @Override
                    public void onBitmapReady(@Nullable Bitmap bitmap) {
                        //去到对应结果界面
                        PreviewActivity.isCamera = true;
                        PreviewActivity.resultImg = bitmap;
                        startActivity(PreviewActivity.class);
                    }
                });
            }

            @Override
            public void onVideoRecordingStart() {

            }

            @Override
            public void onVideoRecordingEnd() {

            }

            @Override
            public void onVideoTaken(@NonNull VideoResult result) {

            }
        });
    }

    //反转镜头
    private void reversalLens() {
        Facing curFacing = mDataBinding.cameraView.getFacing();
        if (curFacing == Facing.BACK) {
            mDataBinding.cameraView.setFacing(Facing.FRONT);
        } else {
            mDataBinding.cameraView.setFacing(Facing.BACK);
        }
    }

    private void updateOnCameraOpened(CameraOptions options) {
        mCameraOptions = options;
        List<Flash> flashList = new ArrayList<>(options.getSupportedFlash());
        Collections.sort(flashList, new Comparator<Flash>() {
            @Override
            public int compare(Flash o1, Flash o2) {
                return o1.ordinal() - o2.ordinal();
            }
        });
        mFlashList = flashList;
        LevelListDrawable levelListDrawable = new LevelListDrawable();
        int drawableId = 0;
        for (Flash flash : flashList) {
            switch (flash) {
                case OFF:
                    drawableId = R.drawable.asgabguabfd;
                    break;
                case ON:
                    drawableId = R.drawable.adakai;
                    break;
                case AUTO:
                    drawableId = R.drawable.azidong;
                    break;
                case TORCH:
                    drawableId = R.drawable.achangliang;
                    break;
            }
            if (drawableId != 0) {
                levelListDrawable.addLevel(flash.ordinal(), flash.ordinal(), getDrawable(drawableId));
            }
        }
        mDataBinding.ivCameraFlash.setImageDrawable(levelListDrawable);
        int level = mDataBinding.cameraView.getFlash().ordinal();
        mDataBinding.ivCameraFlash.setImageLevel(level);
    }

    private void clickFlash() {
        if (mFlashList == null || mFlashList.size() == 0) {
            return;
        }

        Drawable drawable = mDataBinding.ivCameraFlash.getDrawable();
        if (!(drawable instanceof LevelListDrawable)) {
            return;
        }
        LevelListDrawable levelListDrawable = (LevelListDrawable) drawable;
        int level = levelListDrawable.getLevel();
        Flash nextFlash = null;
        for (int i = 0; i < mFlashList.size(); i++) {
            if (level == mFlashList.get(i).ordinal()) {
                if (i < mFlashList.size() - 1) {
                    nextFlash = mFlashList.get(i + 1);
                } else {
                    nextFlash = mFlashList.get(0);
                }
                break;
            }
        }
        if (nextFlash != null) {
            levelListDrawable.setLevel(nextFlash.ordinal());
            mDataBinding.cameraView.setFlash(nextFlash);
        }
    }

    //获取视频和图片数据
    private void getData() {
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.PHOTO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntities) {
                if (selectMediaEntities.size() > 0) {
                    imgPath=selectMediaEntities.get(0).getPath();
                    Glide.with(mContext).load(imgPath).into(mDataBinding.ivSelPic);
                }
            }
        });

    }

}